<!--
 * @Author: tcosfish
 * @Date: 2022-08-26 12:08:03
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-08-26 16:08:30
 * @FilePath: \ry-frontend\src\components\Download.vue
-->
<script setup lang="ts">
import { ElButton, ElMessage } from "element-plus"

const props = defineProps<{
  filename: string
  action: string
}>()

// * 所谓文件下载, 便是模拟点击a标签的过程
const downloadFile = async () => {
  const rawFile = await fetch(props.action + props.filename, {
    method: "get",
  })
  if (rawFile.status === 200) {
    const blob = await rawFile.blob() // 将可读文件流转化为类文件对象
    const href = URL.createObjectURL(blob) // 将类文件对象变成 DOMString(一个指向参数内容的 URL)
    const body = document.body
    const a = document.createElement("a")
    a.download = props.filename
    a.href = href
    body.appendChild(a)
    a.click()
    URL.revokeObjectURL(href)
    body.removeChild(a)
  } else {
    ElMessage.error("文件获取失败, 请检查获取的文件名!")
  }
}
</script>

<template>
  <div>
    <el-button type="success" @click="downloadFile">获取文件</el-button>
  </div>
</template>

<style scoped lang="scss"></style>
